﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace GoodMan.Infrastructure.Entities.Repository
{
    [Table("T_ProductRepertory")]
    public class T_ProductRepertory : IEntity<T_ProductRepertory>
    {
        [Key]
        [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public int ProductId { get; set; }
        public int CollegeId { get; set; }
        public int DormitoryId { get; set; }
        public int Remain { get; set; }

        public override T_ProductRepertory Find(string key)
        {
            int id = Int32.Parse(key);
            return Find(c => c.Id == id);
        }

        public override T_ProductRepertory Find(System.Linq.Expressions.Expression<Func<T_ProductRepertory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.ProductRepertory.FirstOrDefault(where);
                if (item != null)
                {
                    this.CollegeId = item.CollegeId;
                    this.DormitoryId = item.DormitoryId;
                    this.Id = item.Id;
                    this.ProductId = item.ProductId;
                    this.Remain = item.Remain;
                    return this;
                }
                return null;
            }
        }

        public override bool Any(System.Linq.Expressions.Expression<Func<T_ProductRepertory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                return ctx.ProductRepertory.Any(where);
            }
        }

        public override T_ProductRepertory FindLast(System.Linq.Expressions.Expression<Func<T_ProductRepertory, bool>> where)
        {
            using (Context ctx = new Context())
            {
                var item = ctx.ProductRepertory.OrderByDescending(c=>c.Id).FirstOrDefault(where);
                if (item != null)
                {
                    this.CollegeId = item.CollegeId;
                    this.DormitoryId = item.DormitoryId;
                    this.Id = item.Id;
                    this.ProductId = item.ProductId;
                    this.Remain = item.Remain;
                    return this;
                }
                return null;
            }
        }
    }
}
